#!/usr/bin/env groovy
package com.yidao.www

def robotAutoBuild(robot, arch, branch, distro, clean, version){

    def date = new Date()
    def buildVersion
    if(robot == 'D200'){
        buildVersion = version + '.' + date.format('yyyyMMddHHmm') + '_' + BUILD_NUMBER
    }else{
        buildVersion = version
    }
    def robotBuildProfile = robotBuildProfile(robot, arch, branch, distro, buildVersion)
    def label = robotBuildProfile.label.get(arch).get(distro) + '_' + BUILD_NUMBER
    def image = robotBuildProfile.image.get(arch).get(distro)
    def volumes = robotBuildProfile.volumes.get(arch).get(distro)
    def gitInfo = robotBuildProfile.gitUrl.get(arch)
    def cherryPickDir = robotBuildProfile.cherryPickDir
    def artifactDir = robotBuildProfile.artifactDir
    def artifactName = robotBuildProfile.artifactName
    def artifact =  artifactDir + artifactName
    def buildScript = robotBuildProfile.buildScript
    def cleanScript = robotBuildProfile.cleanScript
    def packageScript = robotBuildProfile.packageScript
    def artifactory = robotBuildProfile.artifactory + '/build'
    def cleanCmd = robotBuildProfile.cleanCmd
    def webhookUrl = robotBuildProfile.webhookUrl
    def base = new base()
    def notification = new notification()
    def jobName = JOB_NAME
    def buildNumber = BUILD_NUMBER
    def jobUrl = JOB_URL
    def logUrl = BUILD_URL + 'console'
    def username = ''
    def deployTarget = base.backupFolder(artifactory, robot, branch, date)
    def server = Artifactory.server 'jfrog-artifactory'
    def srverUrl = server.url
    def storageURL

    def gerrit = new gerrit()
    def map = gerrit.getGerritResource(robot)
    def list = []
    map.each{ x, y ->
        list.add(x)
    }
    def choice = list.join(',')

    properties([
        parameters([
            booleanParam(description: '勾选为全量编译，会清除 install build devel 等文件夹内容', name: 'CLEAN'),
            extendedChoice(multiSelectDelimiter: ',', name: 'REFSPEC', quoteValue: false, saveJSONParameterToFile: false, type: 'PT_CHECKBOX', value: choice, visibleItemCount: 20)
        ])
    ])
    def refsLists = params.REFSPEC

    println '============================================== BUILD INFO =============================================='
    println robotBuildProfile
    println "label: ${label}"
    println "image: ${image}"
    println "volumes: ${volumes}"
    println "gitInfo: ${gitInfo}"
    println "artifactDir: ${artifactDir}"
    println "artifactName: ${artifactName}"
    println "artifact: ${artifact}"
    println "buildScript: ${buildScript}"
    println "packageScript: ${packageScript}"
    println "artifactory: ${artifactory}"
    println '========================================================================================================'

    podTemplate(
        cloud: 'kubernetes',
        containers: [
            containerTemplate(
                image: image,
                name: 'jnlp',
                ttyEnabled: true,
                alwaysPullImage: true,
                workingDir: '/home/jenkins/agent')
        ],
        label: label,
        name: 'yidao',
        namespace: 'kube-jenkins',
        volumes: volumes) {

            node(label){

                stage('checkout'){
                    storageURL = srverUrl + '/' + deployTarget
                    try{
                        base.gitRepos(gitInfo, branch)
                    }catch(e){
                        println '[ERROR] 代码克隆失败!'
                        println e
                        currentBuild.result = 'FAILURE'
                        base.influxDb()
                        error e.getMessage()
                    }
                }

                if(refsLists){
                    stage('cherry-pick'){
                        println '==================cherry-pick=================='
                        def refs = refsLists.split(',')
                        def lst = Arrays.asList(refs)
                        def revlst = lst.reverse()
                        dir(cherryPickDir){
                            revlst.each{ x ->
                                println 'refspec: ' + x
                                def cherryPickCmd = map.get(x)
                                println 'cmd: ' + cherryPickCmd
                                base.scriptStatus(cherryPickCmd)
                            }
                        }
                        println '==================cherry-pick=================='
                    }

                    stage('build'){
                        if(clean){
                            def status = base.scriptStatus(cleanScript)
                        }
                        try{
                            def status = base.scriptStatus(buildScript)
                            if(status != 0){
                                currentBuild.result = 'FAILURE'
                                base.influxDb()
                                error '[ERROR] 编译失败!'
                            }
                        }catch(e){
                            println '[ERROR] 编译失败!'
                            println e
                            currentBuild.result = 'FAILURE'
                            base.influxDb()
                            notification.wechatNotification(webhookUrl, jobName, buildNumber, jobUrl, logUrl, '', currentBuild.currentResult)
                            error e.getMessage()
                        }
                    }

                    stage('package'){
                        try{
                            def status = base.scriptStatus(packageScript)
                            if(status != 0){
                                currentBuild.result = 'FAILURE'
                                base.influxDb()
                                error '[ERROR] 打包失败!'
                            }
                        }catch(e){
                            println '[ERROR] 打包失败!'
                            println e
                            currentBuild.result = 'FAILURE'
                            base.influxDb()
                            error e.getMessage()
                        }

                    }

                    stage('upload'){
                        print "artifact: ${artifact}"
                        print "deployTarget: ${deployTarget}"
                        try{
                            base.fileUpload(artifact, deployTarget)
                        }catch(e){
                            println "[ERROR] 上传失败!"
                            println e
                            currentBuild.result = 'FAILURE'
                            base.influxDb()
                            error e.getMessage()
                        }
                    }

                    stage('clean'){
                        def status = base.scriptStatus(cleanCmd)
                        if(status != 0){
                            println "[ERROR] 清理失败!"
                        }
                    }

                    stage('influxDb'){
                        currentBuild.result = 'SUCCESS'
                        base.influxDb()
                    }

                    stage('retrun artifact'){
                        currentBuild.description = """<span>存储地址:<a href=${storageURL}>${storageURL}</a></span>"""
                        return deployTarget
                    }
                }

            }
        }
}